package net.zjitc.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import net.zjitc.utils.APIResponse;
import net.zjitc.utils.JwtTokenUtil;
import org.springframework.web.servlet.HandlerInterceptor;

public class AdminInterceptor implements HandlerInterceptor {

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("jwt");
        System.out.println("token:" + token);
        if (token != null && JwtTokenUtil.validateToken(token) != null) {
            return true;
        }
        response.setContentType("application/json;charset=utf-8");
        APIResponse apiResponse = new APIResponse<>();
        apiResponse.fail(2,"用户未登录或登录已过期",null);
        String jsonResponse = objectMapper.writeValueAsString(apiResponse);
        response.getWriter().print(jsonResponse);
        return false;
    }

}